import * as Cesium from 'cesium'

let stations = []

// 渲染带光锥的地铁站
export const renderStation = (viewer, options) => {
  const { lng, lat, height = 0 } = options.position
  const position = Cesium.Cartesian3.fromDegrees(lng, lat, height)

  // 光锥
  const conePrimitive = viewer.scene.primitives.add(
    new Cesium.Primitive({
      geometryInstances: new Cesium.GeometryInstance({
        geometry: new Cesium.CylinderGeometry({
          length: 700,
          topRadius: 0,
          bottomRadius: 100,
          vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
        }),
        attributes: {
          color: Cesium.ColorGeometryInstanceAttribute.fromColor(
            options.color || Cesium.Color.RED
          ),
        },
      }),
      appearance: new Cesium.PerInstanceColorAppearance({
        translucent: true,
      }),
      modelMatrix: Cesium.Transforms.eastNorthUpToFixedFrame(position),
    })
  )
  // 向上偏移一半高度
  conePrimitive.modelMatrix = Cesium.Matrix4.multiplyByTranslation(
    conePrimitive.modelMatrix,
    new Cesium.Cartesian3(0, 0, 350),
    new Cesium.Matrix4()
  )

  // 底座圆
  const bottomCircleEntity = viewer.entities.add({
    position,
    ellipse: {
      semiMajorAxis: 100,
      semiMinorAxis: 100,
      material: options.color || Cesium.Color.RED,
      outline: true,
      outlineColor: Cesium.Color.WHITE,
    },
  })

  stations.push({
    name: options.name,
    conePrimitive,
    bottomCircleEntity,
    position,
  })
  return { name: options.name, conePrimitive, bottomCircleEntity }
}

export const removeStation = (viewer, name) => {
  const station = stations.find((s) => s.name === name)
  if (station) {
    viewer.scene.primitives.remove(station.conePrimitive)
    viewer.entities.remove(station.bottomCircleEntity)
    stations = stations.filter((s) => s.name !== name)
  }
}

export const getStations = () => stations

// 1. 视角跳转至线路
export const flyToLine = (viewer, lineName) => {
  // 这里假设有 getLineCenter 方法
  const lineCenter = getLineCenter(lineName)
  if (lineCenter) {
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(
        lineCenter.lng,
        lineCenter.lat,
        1000
      ),
      duration: 2,
      orientation: {
        heading: Cesium.Math.toRadians(0),
        pitch: Cesium.Math.toRadians(-40),
        roll: 0.0,
      },
    })
  }
}

// 2. 线路闪烁
let flashInterval = null
export const binkLineByName = (viewer, lineName) => {
  clearInterval(flashInterval)
  // 假设线路以 entity 方式存储
  const lineEntity =
    viewer.entities.getById && viewer.entities.getById(lineName)
  let isVisible = true
  if (lineEntity) {
    flashInterval = setInterval(() => {
      lineEntity.show = isVisible
      isVisible = !isVisible
    }, 500)
  }
}

// 3. 移除所有圆柱
export const removeAllCones = (viewer) => {
  viewer.entities.values.forEach((entity) => {
    if (entity.name && entity.name.startsWith('活动圆柱')) {
      viewer.entities.remove(entity)
    }
  })
}

// 4. 添加渐变圆柱
export const addGradientCone = (viewer, options) => {
  const { position, color, name, height = 1000, radius = 200 } = options
  const entity = viewer.entities.add({
    name,
    position: Cesium.Cartesian3.fromDegrees(
      position.lng,
      position.lat,
      position.height
    ),
    cylinder: {
      length: height,
      topRadius: 0,
      bottomRadius: radius,
      material: color,
      outline: false,
    },
  })
  return entity
}

// 5. 视角跳转到圆柱
export const flyToCone = (viewer, coneName) => {
  const cone = viewer.entities.values.find((entity) => entity.name === coneName)
  if (cone) {
    viewer.flyTo(cone, {
      offset: new Cesium.HeadingPitchRange(
        Cesium.Math.toRadians(40),
        Cesium.Math.toRadians(-40),
        500
      ),
      duration: 2,
    })
  }
}

// 辅助：获取线路质心（需根据实际数据实现）
function getLineCenter(lineName) {
  // 这里应从线路数据中获取所有站点坐标，计算平均值
  // 示例返回武汉中心点
  return { lng: 114.32, lat: 30.71 }
}
